package com.zhengaz.service.blog.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhengaz.common.core.vo.PageVo;
import com.zhengaz.service.blog.dto.BlogArticleDto;
import com.zhengaz.service.blog.dto.BlogArticleQueryDto;
import com.zhengaz.service.blog.entity.BlogArticleEntity;
import com.zhengaz.service.blog.mapper.BlogArticleMapper;
import com.zhengaz.service.blog.service.BlogArticleService;
import com.zhengaz.service.blog.vo.BlogArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author zhengzg
 * @create 2023-11-26 14:21
 */
@Service
@Slf4j
public class BlogArticleServiceImpl extends ServiceImpl<BlogArticleMapper, BlogArticleEntity> implements BlogArticleService {
    @Override
    public PageVo<List<BlogArticleVo>> getBlogArticleList(BlogArticleQueryDto dto) {
        IPage<BlogArticleVo> page = new Page<>(dto.getPageNum(), dto.getPageSize());

        List<BlogArticleVo> blogArticleListVos = this.baseMapper.selectBlogArticleListVo(page, dto.getTypeId(), dto.getKeyWord());

        PageVo<List<BlogArticleVo>> pageVo = new PageVo<>();
        if (CollUtil.isEmpty(blogArticleListVos)) {
            pageVo.setData(new ArrayList<>());
            return pageVo;
        }

        pageVo.setTotal(page.getTotal());
        pageVo.setPageSize(page.getSize());
        pageVo.setCurrent(page.getCurrent());
        pageVo.setData(blogArticleListVos);
        return pageVo;
    }

    @Override
    public BlogArticleVo getBlogArticleDetail(Integer id) {
        return this.baseMapper.selectBlogArticleVo(id);
    }

    @Override
    public Integer saveBlogArticle(BlogArticleDto dto) {
        if (Objects.isNull(dto.getTypeId()) || StrUtil.isBlank(dto.getTitle()) || StrUtil.isBlank(dto.getArticleContent())) return -1;

        BlogArticleEntity entity = new BlogArticleEntity();
        BeanUtils.copyProperties(dto, entity);
        entity.setCreateTime(LocalDateTime.now());
        entity.setViewCount(0);

        boolean save = this.save(entity);
        return save ? entity.getId() : -1;
    }
}
